package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.entity.Result;
import cn.itcast.pojo.CheckGroup;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @RequestMapping("/findUsername")
    public Result findUsername() {
        //当Spring security 完成认证后 会将当前用户信息保存到框架提供的上下文对象
        //SecurityContextHolder 工具类   getContext获取上下文对象  getAuthentication 认证信息对象  getPrincipal用户对象(security框架提供的)
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = user.getUsername();
        if (username != null) {
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }
    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return userService.findPage(queryPageBean);
    }

    //新建用户
    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('USER_ADD')")//权限校验
    public Result add(@RequestBody cn.itcast.pojo.User user){
        try {
            String password = user.getPassword();
            user.setPassword(passwordEncoder.encode(password));
            userService.add(user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
        return new Result(true, MessageConstant.ADD_USER_SUCCESS);
    }

    //添加角色
    @RequestMapping("/edit")
    @PreAuthorize("hasAuthority('USER_EDIT')")//权限校验
    public Result edit(Integer[] roleIds,Integer userId){
        try {
            userService.edit(userId,roleIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
    }
}
